/**
 * 
 */
package jvs.peer.xmpp;

import jvs.peer.io.MessageConstant;
import jvs.peer.util.Log;

import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
 * @author qiangli
 *
 */
public class XmppSessionFilter implements PacketFilter {
	private int type;
	/**
	 * @param i 
	 * 
	 */
	public XmppSessionFilter(int type) {
		this.type = type;
	}

	public boolean accept(Packet packet) {
		if (Log.DEBUG) {
			Log.log(this, " accepting:  type: "+ type +" from: "+ packet.getFrom() + " to: "
				+ packet.getTo());
		}
		if (XmppUtil.isLoopback(packet)) {
			return false;
		}
		if (!(packet instanceof Message)) {
			return false;
		} 
		Message msg = (Message) packet;
		if (msg.getType().equals(Message.Type.chat) == false) {			
			return false;
		}
		Object prop = msg.getProperty(MessageConstant.SHELL);
		if (Log.DEBUG) {
			Log.log(this, " accepting:  type: "+ type +" prop: "+prop+" from: "+ packet.getFrom() + " to: "
				+ packet.getTo());
		}
		String tid = msg.getThread();
		String from = msg.getFrom();
		
		if (Log.DEBUG) {
			Log.log(this, " accepting:  thread: "+ tid +" prop: "+prop+" from: "+ packet.getFrom() + " to: "
				+ packet.getTo());
		}
		if (from == null) {
			return false;
		}
		switch (type) {
		case MessageConstant.response:
			if (prop == null || prop.equals(MessageConstant.response) == false){
				return false;
			}
			break;
		case MessageConstant.request:
		default:
			if (prop != null && prop.equals(MessageConstant.response) == true){
				return false;
			}
		}
		if (Log.DEBUG) {
			Log.log(this, " accepted:  type: "+ type +" from: "+ packet.getFrom() + " to: "
				+ packet.getTo());
		}
		return true;
	}
}
